package rs.mbs2.epics.server.servlet;

import java.io.IOException;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import rs.mbs2.epics.server.entity.Album;
import rs.mbs2.epics.server.entity.User;
import rs.mbs2.epics.server.servlet.util.Validation;
import rs.mbs2.epics.server.session.dao.localinterface.AlbumDaoLocal;
import rs.mbs2.epics.server.session.dao.localinterface.UserDaoLocal;

@SuppressWarnings("serial")
public class CreateAlbumController extends HttpServlet {
	
	private static Logger log = Logger.getLogger(CreateAlbumController.class);
	
	@EJB
	private AlbumDaoLocal albumDao;
	
	@EJB
	private UserDaoLocal userDao;
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String title = request.getParameter("title");
		String description = request.getParameter("description");
		boolean publicVisible = request.getParameter("public") != null;	// ako nije štiklirano biće true
		
		boolean isValid = true;
		
		isValid = Validation.validateString(title);
		//isValid = Validation.validateString(description);
		
		if(isValid && title.equalsIgnoreCase("favorites"))
			isValid = false;
			
		
		if(!isValid) {
			log.info(new Date() + ": Uneti nevalidni podaci u kreiranju albuma.");
			response.sendRedirect(response.encodeRedirectURL("./createAlbum.jsp"));
			return;
		}

		User u = (User) request.getSession().getAttribute("user");
		User user = userDao.findById(u.getId());
		
		Album album = new Album(title,description,publicVisible,user);
		albumDao.persist(album);
		
		
		List<Album> albumsList = albumDao.findAllAlbumsFromUser(user.getId());
		Set<Album> albums = new HashSet<Album>();
		
		if(albumsList != null) {
			albums.addAll(albumsList);
		}
		
		user.setAlbums(albums);

		userDao.merge(user);
		
		
		log.info(new Date() + ": Kreiran album: " + album.getTitle() + "(USER ID: " + user.getId() + ")");		
		getServletContext().getRequestDispatcher("/HomeController").forward(request, response);
		
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}
}
